package com.lx.cloudzuul.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lx.bean.Result;
import com.lx.dm.util.JWTUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "post";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        // 127.0.0.1/user/login/login?...
        String path = request.getServletPath();
        System.out.println("path = " + path);
        return path.matches("/[^/]+/login/login");
    }

    @Override
    public Object run() throws ZuulException {
        // 获取当前请求上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        String json = " ";
        HttpServletResponse response = ctx.getResponse();

        // 把json转换为对象
        ObjectMapper mapper = new ObjectMapper();
        try (InputStream inputStream = ctx.getResponseDataStream();
             InputStreamReader inputStreamReader =
                     new InputStreamReader(inputStream, "UTF-8")){
            char[] chars = new char[1024];
            int cnt = inputStreamReader.read(chars);
            json = new String(chars, 0, cnt);
            Result result = mapper.readValue(json, Result.class);
            if (result.getCode() == 1) {
                // 构建jwt
                String jwt = JWTUtil.createJWT(30, (Map<String, Object>) result.getData());
                //放行
                response.addHeader("Authorization", jwt);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 重新将 json 写入 返回响应对象
        ctx.getResponse().setContentType("application/json;charset=utf-8");
        ctx.setResponseBody(json);
        return null;
    }
}
